﻿using Castle.DynamicProxy;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Framework.LinkTrackingLog.MyTest
{
    /// <summary>
    /// 方法监控拦截器
    /// </summary>
    public class MethodMonitoringInterceptor : IInterceptor
    {
        private IMethodMonitoringService _monitoringService;
        public MethodMonitoringInterceptor(IMethodMonitoringService monitoringService) 
        {
            _monitoringService = monitoringService;
        }

        /// <summary>
        /// 拦截方法
        /// </summary>
        /// <param name="invocation"></param>
        /// <exception cref="NotImplementedException"></exception>
        public void Intercept(IInvocation invocation)
        {
            //获取类特性
            var attrClass = invocation.TargetType.GetCustomAttribute<MethodMonitoringAttribute>();
            //获取方法特性
            var attr = invocation.Method.GetCustomAttribute<MethodMonitoringAttribute>();
            bool attrClassMonitor = attrClass?.Monitor ?? false;
            bool attrMonitor = attr?.Monitor ?? false;
            if ((!attrClassMonitor && !attrMonitor) || !attrMonitor)
            {
                //已被标记不监控，则直接执行
                invocation.Proceed();
                return;
            }

            using (_monitoringService.MonitoringService(invocation.Method.Name, invocation.TargetType.Name))
            {
                try
                {
                    invocation.Proceed();
                }
                catch(Exception e)
                {
                    _monitoringService.Execute(e);
                    throw;
                }
            }
        }
    }
}
